package ru.smc.hogwarts.servlets.rooms;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Room;
import ru.smc.hogwarts.model.Student;

public class RoomsInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
       
    public RoomsInfo() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
    	
    	long id = 0;
		
		try {
			id = Long.parseLong(request.getParameter("id"));
		} catch (NumberFormatException e) {}
    	
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
    	
    	Room room = em.find(Room.class, id);
		
		if (room == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {
	    	List<Student> students = em.createQuery("select p from Student p where p.room.id like '"+ id +"'").getResultList();
	    	request.setAttribute("students", students);
	    	
	    	request.setAttribute("id", id);
	    	
	    	String error;
	    	if (session.getAttribute("error") != null) {
	    		error = (String)session.getAttribute("error");
	    		session.removeAttribute("error");
	    	} else {
	    		error = "";
	    	}
	    	
	    	request.setAttribute("error", error);
	    	request.getRequestDispatcher("/pages/rooms/roomInfo.jsp").forward(request, response);
		}
	    
		em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
